#!/usr/bin/env python2

import os
import sys
import socket
import time
import subprocess
import fcntl
import types
import errno
import getopt
import random
import threading

from daemon import Daemon
from config import Config
from utils import Exp, _dmsg, _dwarn, _derror, _str2dict, _getrack, _exec_shell

lich = Config().lich
crons = [
    ['lich.node --dump_io', 20, None],
    ['lich.node --dump_clean', 3600, None],
    #['lich.node --recover', 60 * 10, "recover.log"],
    #['lich.node --metabalance', 60 * 60, "metabalance.log"],
    #['lich.node --chunkbalance', 60 * 60 * 8, "chunkbalance.log"],
]

class Lich_Cron(Daemon):
    def __init__(self, config):
        self.config = config
        os.system('mkdir -p ' + self.config.home + '/tmp')
        os.system('mkdir -p ' + self.config.home + '/log')
        pidfile = '/var/run/lich_cron.pid'
        log = self.config.home + '/log/lich_cron.log'
        os.system('touch ' + log)
        super(Lich_Cron, self).__init__(pidfile, '/dev/null', log, log, 'lich_cron')

    def __cron(self, func, interval, log):
        #func = args[0]
        #interval = args[1]
        #log = args[2]

        if (log):
            cmd = "%s >> %s/log/%s" % (func, self.config.home, log)
        else:
            cmd = func

        _dmsg("init cron '%s' " % (cmd))

        s = random.randrange(0, interval)
        time.sleep(s)

        while(1):
            _dmsg("begin '%s' " % (cmd))

            try:
                ret = _exec_shell(cmd)
            except:
                _derror("exec %s fail" % (cmd))
                time.sleep(interval)
                continue;

            _dmsg("end '%s' " % (cmd))

            time.sleep(interval)

    def run(self):
        for i in crons:
            t = threading.Thread(target=self.__cron, args=i)
            t.start()

        while (1):
            time.sleep(10)
            #_dmsg("lich_cron running")

def usage():
    print ("usage:")
    print (sys.argv[0] + " --start")
    print (sys.argv[0] + " --stop")
    print (sys.argv[0] + " --test")
    print (sys.argv[0])

def main():
    op = ''
    ext = None
    try:
        opts, args = getopt.getopt(
                sys.argv[1:], 
            'h', ['start', 'stop', 'help', 'test']
                )
    except getopt.GetoptError, err:
        print str(err)
        usage()

    for o, a in opts:
        if o in ('--help'):
            usage()
            exit(0)
        elif o == '--start':
            op = o
            #lich_cron.start()
        elif o == '--stop':
            op = o
        elif o == '--test':
            op = o
        else:
            assert False, 'oops, unhandled option: %s, -h for help' % o
            exit(1)

    config = Config()
    lich_cron = Lich_Cron(config)
    if (op == '--start'):
        lich_cron.start()
    elif (op == '--stop'):
        lich_cron.stop()
    elif (op == '--test'):
        lich_cron.run()
    else:
        assert False, 'oops, unhandled option: %s, -h for help' % o
        exit(1)


if __name__ == '__main__':
    if (len(sys.argv) == 1):
        usage()
    else:
        main()
